package com.woniuxy.config;

import com.woniuxy.security.LoginFailHandler;
import com.woniuxy.security.LoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;


import javax.annotation.Resource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder CreatePasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭基础的认证登录
        http.httpBasic().disable()
                //跨站伪造攻击拦截器关闭
                .csrf().disable()
                //配置认证授权的拦截器规则
                .authorizeRequests()
                //放行
                .antMatchers("/api/**","/account/loginerror","/login","/**").permitAll()
//                .antMatchers(HttpMethod.OPTIONS).permitAll()
//                .antMatchers("/swagger-ui.html","/v2/api-docs","/webjars/**",
//                        "/swagger-resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //进行账号密码登录方式的设置
                .formLogin()
                //未登录的跳转地址
                .loginPage("/account/loginerror")
                .loginProcessingUrl("/login")
                //登录成功的跳转
                .successHandler(loginSuccessHandler)
                //登录失败的跳转
                .failureHandler(new LoginFailHandler())
                .and()
                .cors().configurationSource(getCorsFilter());
    }
    public UrlBasedCorsConfigurationSource getCorsFilter(){
        UrlBasedCorsConfigurationSource cfs = new UrlBasedCorsConfigurationSource();
        CorsConfiguration cors = new CorsConfiguration();
        cors.addAllowedHeader("*");
        cors.addAllowedOriginPattern("*");
        cors.addAllowedMethod("*");
        cors.setAllowCredentials(true);
        cfs.registerCorsConfiguration("/**",cors);
        return cfs;
    }
}
